package com.ntt.benew.dictionary.utils;

import android.util.Log;

import androidx.annotation.Nullable;

import com.ntt.benew.dictionary.NttDictionaryManager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {
    public static final String USER_AGENT = "NTT-Device-R2-";

    /**
     * 发送post请求，根据 Content-Type 返回不同的返回值
     *
     * @param url
     * @param header
     * @param body
     * @return
     */
    public static Map<String, Object> doPost2(String url, Map<String, String> header, String body) {
        Map<String, Object> resultMap = new HashMap<>();
        PrintWriter out = null;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 设置 header
            for (String key : header.keySet()) {
                httpURLConnection.setRequestProperty(key, header.get(key));
            }
            // 设置请求 body
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            out = new PrintWriter(httpURLConnection.getOutputStream());
            // 保存body
            out.print(body);
            // 发送body
            out.flush();
            if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
                System.out.println("Http 请求失败，状态码：" + httpURLConnection.getResponseCode() + "，错误信息：" + br.readLine());
                return null;
            }
            // 获取响应header
            String responseContentType = httpURLConnection.getHeaderField("Content-Type");
            if ("audio/mpeg".equals(responseContentType)) {
                // 获取响应body
                byte[] bytes = toByteArray(httpURLConnection.getInputStream());
                resultMap.put("Content-Type", "audio/mpeg");
                resultMap.put("sid", httpURLConnection.getHeaderField("sid"));
                resultMap.put("body", bytes);
            } else {
                // 设置请求 body
                BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line;
                StringBuilder result = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                resultMap.put("Content-Type", "text/plain");
                resultMap.put("body", result.toString());

            }
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    public static String sendPostHttp(String mUrl, String content, String token) {
        Log.d("HttpManage", "sendPostHttp: 开始请求 -》 " + mUrl);
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String body = "{\"content\":\"" + content + "\"}";
        try {
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            //设置连接超时时间（毫秒）
            connection.setConnectTimeout(20000);
            //设置读取超时时间（毫秒）
            connection.setReadTimeout(10000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Accept", "application/json");//设置参数类型是json格式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//设置参数类型是json格式
            connection.setRequestProperty("deviceId", NttDictionaryManager.INSTANCE.getDeviceId());
            connection.setRequestProperty("Authorization", "Bearer " + token);
            connection.setRequestProperty("User-Agent", USER_AGENT + NttDictionaryManager.INSTANCE.getDeviceVersion());
            connection.setRequestProperty("X-Device-User-Agent", USER_AGENT + NttDictionaryManager.INSTANCE.getDeviceVersion());


            connection.connect();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            //返回输入流
            InputStream in = connection.getInputStream();

            //读取输入流
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            Log.d("HttpManage", "sendPostHttp: data -> " + result.toString());
            return result.toString();

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("HttpManage", "sendPostHttp: e -> " + e.getMessage());
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {//关闭连接
                connection.disconnect();
            }
        }
    }

    public static @Nullable String sendGetHttp(String mUrl, Map<String, String> header) {
        Log.d("HttpManage", "sendGetHttp: 开始请求 -》 " + mUrl);
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            if (header != null) {
                // 设置 header
                for (String key : header.keySet()) {
                    connection.setRequestProperty(key, header.get(key));
                }
            }
            //设置请求方法
            connection.setRequestMethod("GET");
            //设置连接超时时间（毫秒）
            connection.setConnectTimeout(20000);
            //设置读取超时时间（毫秒）
            connection.setReadTimeout(10000);

            //返回输入流
            InputStream in = connection.getInputStream();

            //读取输入流
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            Log.d("HttpManage", "sendGetHttp: data -> " + result.toString());
            return result.toString();

        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
            Log.e("HttpManage", "sendGetHttp: e -> " + e.getMessage());
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {//关闭连接
                connection.disconnect();
            }
        }
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param header
     * @param body
     * @return
     */
    public static @Nullable String doPost1(String url, Map<String, String> header, String body) {
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            if (header != null) {
                // 设置 header
                for (String key : header.keySet()) {
                    httpURLConnection.setRequestProperty(key, header.get(key));
                }
            }
            // 设置请求 body
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            out = new PrintWriter(httpURLConnection.getOutputStream());
            // 保存body
            out.print(body);
            // 发送body
            out.flush();
            if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) {
                System.out.println("Http 请求失败，状态码：" + httpURLConnection.getResponseCode());
                return null;
            }

            // 获取响应body
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    /**
     * 流转二进制数组
     *
     * @param in
     * @return
     * @throws IOException
     */
    private static byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}
